<template>
  <div>
    <div id="container" v-if="status == '0'">
      <img class='logo' :src="hsLogo">
      <form>
        <div class="test_name">
          考试类型: {{examInfo.title}}
        </div>
        <div class="test_time flex_between">
          考试时间: {{examTime}}
        </div>
        <div class="test_time flex_between" v-if="examInfo.examAddress">
          考试地点: {{examInfo.examAddress}}
        </div>
        <div class="mobile_num">
          <input maxlength="11"
                 type="tel"
                 placeholder="请输入手机号码"
                 v-model="mobile"
                 @keyup="mobileFilter"
          />
        </div>
        <div class="auth_num">
          <input
            maxlength="6"
            type="text"
            placeholder="请输入验证码"
            v-model="authCode"
            @keyup="authCodeFilter"
          />

          <p id="auth" :class="countingStatus == '0' ? 'fetch_auto_code' : 'counting_auto_code'"
             @click="getAuthCode({mobile})">{{btnAuth}}</p>

        </div>

        <div id="login" @click="onApplyClick(examId,mobile,authCode)">确认报名</div>

      </form>
    </div>
    <div v-else>
      <ApplyResult :result=signResult :examInfo=examInfo :examTime=examTime></ApplyResult>
    </div>
  </div>
</template>

<script>
  import {mapActions, mapGetters, mapMutations, mapState} from '../../../../static/js/vuex.js'
  import {applyPageModule} from './ApplyStore'
  import store from '../../../repo/store/store'
  import ApplyResult from './applyresult/applyresult-m.vue'
  import {Toast} from "vant";
  import ExamApi from "../../../repo/api/ExamAPI";
  import timeTool from "./timeTool"

  const storePath = 'page/apply'
  const storeNameSpace = ['page', 'apply']
  const _hasErrorAuthCode = authCode => !(authCode && authCode.length == 6)
  const _hasErrorMobile = mobile => {
    return !(mobile && mobile.length === 11 && mobile.startsWith('1'))
  }
  export default {
    metaInfo: {title: '统筹考试报名'},
    components: {
      ApplyResult
    },
    data() {
      return {
        status: '0', // 0表示在报名页,1表示在结果页
        mobile: '',
        authCode: '',
        countingStatus: '0',
        signResult: {},
        examInfo: {
          id: '',
          title: '',
          //标题最多十七个字符
          examAddress: '',
          //地址最多十七个字符
          examStartTime: '',
          examEndTime: '',
        }

      }
    },
    computed: {
      ...mapState(storePath, ['authState', 'countdown']),
      /* 存储的数据,authState, countdown */
      ...mapGetters(storePath, ['btnAuth']),
      ...mapGetters({'hsLogo': 'hsLogoM'}),
      params() {
        return this.$route.params
      },
      examId() {
        return this.params.examId
      },
      examTime() {
        return timeTool.formatExamInfo(this.examInfo)
      }
    },
    watch: {
      authState(nVal) {
        if (nVal === 'counting') {
          // noinspection JSCheckFunctionSignatures
          this.startCountdown()
          this.countingStatus = '1'
          //按钮置灰
        } else if (nVal === 'init') {
          this.setCountdown(0)
        } else if (nVal === 'retry') {
          this.setCountdown(0)
          this.countingStatus = '0'

        }
      }
    },
    beforeRouteEnter(to, form, next) {
      if (!store.hasModule(storeNameSpace)) {
        store.registerModule(storeNameSpace, applyPageModule)
      }
      next()
    },
    created() {
      this.setAuthState('init')
      //初始化setAuthState为init
      this.getExamData()
      this.status = '0'
    },
    destroyed() {
      console.log("applyIndexMDestroyed")
      if (store.hasModule(storeNameSpace)) {
        store.unregisterModule(storeNameSpace)
      }
    },
    methods: {
      //同步请求
      ...mapMutations(storePath, [
        'setCountdown',
        'setAuthState',
      ]),

      //异步请求
      ...mapActions(storePath, [
        'getAuthCode',
        'startCountdown',
      ]),
      mobileFilter() {
        this.mobile = this.mobile.replace(/[^\d]/g, '')
        /* 去除非数字 */
      },
      authCodeFilter() {
        this.authCode = this.authCode.replace(/[^\d]/g, '')
      },
      getExamData() {
        console.log(this.examId)
        ExamApi.getSignInfoByExamId(this.examId).then((res) => {
          console.log(res)
          this.examInfo = res.responseData
        }).catch(error => {
          console.log(error)
        })
      },
      onApplyClick(examId, mobile, authCode) {
        console.log(examId)
        console.log(mobile)
        console.log(authCode)

        if (_hasErrorMobile(mobile)) {
          return Toast('请输入正确的手机号码')
        }
        if (_hasErrorAuthCode(authCode)) {
          return Toast('请输入正确的验证码')
        }
        Toast.loading({
          duration: 0,
          message: '正在提交',
          forbidClick: true,
        });
        ExamApi.submitSign(examId, mobile, authCode).then((res) => {
          this.signResult = res.responseData
          Toast.clear()
          if (this.signResult) {
            if (this.signResult.signStatus) {
              this.status = '1' //进入报名结果页
              return
            }
          } else {
            return
          }
        }).catch((error) => {
          Toast.clear()
        })
      }
    }
  }
</script>

<style scoped>
  #container {
    display: flex;
    height: 100vh;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .logo {
    margin-top: 10px;
    width: 148px;
    object-fit: cover;
    margin-bottom: 24px;
  }

  form {
    display: flex;
    width: 100vw;
    flex-direction: column;
  }

  form > div {
    height: 48px;
    margin-left: 24px;
    margin-right: 24px;
    margin-bottom: 24px;
    border-radius: 4px;
    background: #F7F7F7;
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }

  form input {
    height: 100%;
    flex-grow: 1;
    justify-content: space-between;
    padding-left: 10px;
    font-size: 16px;
    line-height: 16px;
    padding-right: 16px;
  }

  .test_time, .test_name {
    padding-left: 10px;
    font-size: 16px;
  }

  #auth {
    min-width: 100px;
    font-size: 16px;
    line-height: 16px;
    text-align: center;
    padding-top: 16px;
    padding-bottom: 16px;
    padding-right: 16px;
  }

  .fetch_auto_code {
    color: #1DA1F2;
  }

  .counting_auto_code {
    color: #808080;
  }

  #login {
    background-image: linear-gradient(225deg, #3ECFFA 0%, #1DA1F2 100%);
    border-radius: 4px;
    margin-left: 24px;
    margin-right: 24px;
    font-weight: bold;
    font-size: 18px;
    color: #FFFFFF;
    line-height: 16px;
    flex-direction: column;
    justify-content: center;
  }

  /*/deep/ .el-input .el-input__inner {
    height: 48px;
    font-size: 16px;
    background: #F7F7F7;
    border-radius: 4px;
    border: none;
    padding-left: 16px;
    color: black;
}
  /deep/ input::-webkit-input-placeholder {
    color: gray;
}*/
  .auth_num input {
    width: 100px;
  }
</style>
